package com.whiteape.book.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.contract.BookDetailContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.MediaChapterBean;
import com.whiteape.book.model.type.CatalogOrderType;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.presenter.BookDetailPresenter;
import com.whiteape.book.ui.adapter.DetailCatalogAdapter;
import com.whiteape.book.ui.base.BaseMVPActivity;
import com.whiteape.book.utils.DaoDbHelper;
import com.whiteape.book.utils.ScreenUtils;
import com.whiteape.book.utils.StatusBarUtils;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.widget.RefreshLayout;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * Created by newbiechen on 17-5-4.
 */

public class MediaDetailActivity extends BaseMVPActivity<BookDetailContract.Presenter>
        implements BookDetailContract.View {
    public static final String RESULT_IS_COLLECTED = "result_is_collected";

    private static final String TAG = "MediaDetailActivity";
    private static final String EXTRA_BOOK_ID = "extra_book_id";
    private static final String EXTRA_COLLECTION_MEDIA = "extra_media";
    private static final String EXTRA_CATALOG = "extra_catalog";

    private static final int REQUEST_READ = 1;

    @BindView(R.id.refresh_layout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.book_detail_head_rl)
    RelativeLayout mRlHead;
    @BindView(R.id.book_detail_iv_cover)
    ImageView mIvCover;
    @BindView(R.id.book_detail_tv_title)
    TextView mTvTitle;
    @BindView(R.id.book_detail_tv_author)
    TextView mTvAuthor;
    @BindView(R.id.book_detail_tv_type)
    TextView mTvType;
    @BindView(R.id.book_detail_tv_word_count)
    TextView mTvWordCount;
    @BindView(R.id.book_detail_tv_lately_update)
    TextView mTvLatelyUpdate;
    @BindView(R.id.book_list_tv_add_collection)
    TextView mTvAddCollection;
    @BindView(R.id.book_detail_tv_read)
    TextView mTvRead;
    @BindView(R.id.book_detail_tv_brief)
    TextView mTvBrief;
    @BindView(R.id.rv_catalog)
    RecyclerView mRvCatalog;
    @BindView(R.id.tv_detail_chapter_order)
    TextView mTvChapterOrder;
    @BindView(R.id.iv_detail_chapter_order)
    ImageView mIvChapterOrder;
    @BindView(R.id.book_detail_tv_source)
    TextView mTvSource;

    /************************************/
    private CollectionMediaBean mCollBookBean;
    private ProgressDialog mProgressDialog;
    /*******************************************/
//    private String mBookId;
    private boolean isBriefOpen = false;
    private boolean isCollected = false;

    DetailCatalogAdapter mDetailCatalogAdapter;
    List<MediaChapterBean> mData = new ArrayList<>();
    List<MediaChapterBean> mRawData = new ArrayList<>();
    static List<MediaChapterBean> inputChapterBeanList;
    private CatalogOrderType mOrderType = CatalogOrderType.ORDER_ASC;

    public static void startActivity(Context context, CollectionMediaBean bean, List<MediaChapterBean> beanList) {
        Intent intent = new Intent(context, MediaDetailActivity.class);
//        intent.putExtra(EXTRA_BOOK_ID, bookId);
        intent.putExtra(EXTRA_COLLECTION_MEDIA, bean);
        inputChapterBeanList = beanList;
//        intent.putExtra(EXTRA_CATALOG, (Serializable)beanList);
        context.startActivity(intent);
    }

    @Override
    protected int getContentId() {
        return R.layout.activity_media_detail;
    }

    @Override
    protected BookDetailContract.Presenter bindPresenter() {
        return new BookDetailPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        mRefreshLayout.showLoading();
        mRvCatalog.setLayoutManager(new GridLayoutManager(this, 3));
        mDetailCatalogAdapter = new DetailCatalogAdapter(R.layout.item_detail_catalog, mData);
        mRvCatalog.setAdapter(mDetailCatalogAdapter);
        mRvCatalog.setNestedScrollingEnabled(true);

//        ImmersionBar.with(this)
//                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
//                .statusBarColor(R.color.transparent)
//                .init();

//        StatusBarUtils.with(this)
//                .init();
//        mRlHead.setPadding(ScreenUtils.dpToPx(5), StatusBarUtils.getStatusBarHeight(this), 0, 0);

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        if (savedInstanceState != null) {
//            mBookId = savedInstanceState.getString(EXTRA_BOOK_ID);

//            mCollectionMediaBean = getIntent().getParcelableExtra(EXTRA_SHELF_BOOK);
            mCollBookBean = savedInstanceState.getParcelable(EXTRA_COLLECTION_MEDIA);
        } else {
//            mBookId = getIntent().getStringExtra(EXTRA_BOOK_ID);
            mCollBookBean = getIntent().getParcelableExtra(EXTRA_COLLECTION_MEDIA);
        }
        CollectionMediaBean bean = MediaStorageManager.getInstance().getShelfMedia(mCollBookBean.getId());
//        inputChapterBeanList = (List<MediaChapterBean>)getIntent().getSerializableExtra(EXTRA_CATALOG);
        if (bean != null) {
            mCollBookBean = bean;
            isCollected = true;
            mCollBookBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
            mData.addAll(mCollBookBean.getMediaChapterList());
            mRawData.addAll(mData);
        }
        mCollBookBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
    }

    @Override
    protected void setUpToolbar(Toolbar toolbar) {
        super.setUpToolbar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("书籍详情");
        }
    }


    private void initRvEvent() {
        mDetailCatalogAdapter.setOnItemChildClickListener(((adapter, view, position) -> {

            MediaChapterBean bean = mData.get(position);


            switch (mCollBookBean.getMediaType()) {
                case MediaType.MEDIA_TYPE_NOVEL:
                    BookReadActivity.startActivity(this, mCollBookBean, mRawData, isCollected, mOrderType == CatalogOrderType.ORDER_ASC ? position : mRawData.size() - position - 1);
                    break;
                case MediaType.MEDIA_TYPE_COMIC:
                    ComicReadActivity.startActivity(this, mCollBookBean, mRawData, isCollected, bean.getId());
                    break;
                case MediaType.MEDIA_TYPE_VIDEO:
                    break;
            }
        }));
    }

    private void initOrderEvent() {
        mTvChapterOrder.setOnClickListener(view -> orderEvent());
        mIvChapterOrder.setOnClickListener(view -> orderEvent());
    }

    private void orderEvent() {
        switch (mOrderType) {
            case ORDER_ASC:
                mTvChapterOrder.setText(getResources().getString(R.string.wa_book_detail_chapters_order_desc));
                mIvChapterOrder.setImageResource(R.mipmap.ic_detail_chapter_desc);
                mOrderType = CatalogOrderType.ORDER_DESC;
                break;
            case ORDER_DESC:
                mTvChapterOrder.setText(getResources().getString(R.string.wa_book_detail_chapters_order_asc));
                mIvChapterOrder.setImageResource(R.mipmap.ic_detail_chapter_asc);
                mOrderType = CatalogOrderType.ORDER_ASC;
                break;
        }
        Collections.reverse(mData);
        mDetailCatalogAdapter.notifyDataSetChanged();

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        initRvEvent();
        initOrderEvent();

        //可伸缩的TextView
        mTvBrief.setOnClickListener(
                (view) -> {
                    if (isBriefOpen) {
                        mTvBrief.setMaxLines(2);
                        isBriefOpen = false;
                    } else {
                        mTvBrief.setMaxLines(5);
                        isBriefOpen = true;
                    }
                }
        );

        mTvAddCollection.setOnClickListener(
                (V) -> {
                    //点击存储
                    if (isCollected) {
                        //放弃点击
                        addDisposable(MediaStorageManager.getInstance()
                                .deleteCollMediaInRx(mCollBookBean));

                        RxBus.get().post(RxEvent.MEDIA_COLLECTION_ADD, mCollBookBean);

                        mTvAddCollection.setText(getResources().getString(R.string.wa_book_detail_collection));

                        //修改背景
//                        Drawable drawable = getResources().getDrawable(R.drawable.selector_btn_book_list);
//                        mTvAddCollection.setBackground(drawable);
                        //设置图片
//                        mTvAddCollection.setCompoundDrawables(ContextCompat.getDrawable(this, R.drawable.ic_book_list_add), null,
//                                null, null);

//                        isCollected = false;
                    } else {
                        mTvAddCollection.setText(getResources().getString(R.string.wa_book_detail_remove_collection));
                        mPresenter.addToBookShelf(mCollBookBean);

//                        //修改背景
//                        Drawable drawable = getResources().getDrawable(R.drawable.shape_common_gray_corner);
//                        mTvAddCollection.setBackground(drawable);
//                        //设置图片
//                        mTvAddCollection.setCompoundDrawables(ContextCompat.getDrawable(this, R.drawable.ic_book_list_delete), null,
//                                null, null);

//                        isCollected = true;
                    }
                }
        );

        mTvRead.setOnClickListener(

                (v) -> {
                    int mediaType = mCollBookBean.getMediaType();
                    if (mediaType == MediaType.MEDIA_TYPE_NOVEL) {
                        BookReadActivity.inputChapterBeanList = mRawData;
                        startActivityForResult(new Intent(this, BookReadActivity.class)
                                        .putExtra(BookReadActivity.EXTRA_IS_IN_SHELF, isCollected)
                                        .putExtra(BookReadActivity.EXTRA_SHELF_BOOK, mCollBookBean)
//                                        .putExtra(BookReadActivity.EXTRA_CHAPTER_LIST, (Serializable) mRawData)
                                , REQUEST_READ);
                    } else if (mediaType == MediaType.MEDIA_TYPE_COMIC) {

                        ComicReadActivity.inputChapterBeanList = mRawData;
                        startActivityForResult(new Intent(this, ComicReadActivity.class)
                                        .putExtra(ComicReadActivity.EXTRA_IS_IN_SHELF, isCollected)
                                        .putExtra(ComicReadActivity.EXTRA_SHELF_BOOK, mCollBookBean)
//                                        .putExtra(ComicReadActivity.EXTRA_CHAPTERS_LIST, (Serializable) mRawData)
                                , REQUEST_READ);
                    }
                }
        );


    }

    @Override
    protected void startLogic() {
        super.startLogic();
        mRefreshLayout.showLoading();
        if (inputChapterBeanList != null && !inputChapterBeanList.isEmpty()) {
            finishRefresh(mCollBookBean);
            complete();
            return;
        }
        if (isCollected) {
            finishRefresh(mCollBookBean);
            complete();
        } else {
            mPresenter.refreshBookDetail(mCollBookBean);
//            mPresenter.updateWebCatalog(mCollBookBean.getSiteSourceBean(), mCollBookBean);
        }
    }

    @Override
    public void finishRefresh(CollectionMediaBean bean) {
        mCollBookBean = bean;
        mCollBookBean.__setDaoSession(DaoDbHelper.getInstance().getSession());

        //封面
        Glide.with(this)
                .load(bean.getCoverUrl())
                .transition(DrawableTransitionOptions.withCrossFade(200))
                .placeholder(R.mipmap.no_cover_portrait)
//                .error(R.drawable.ic_load_error)

                .centerCrop()


                .into(mIvCover);

        // 圆角和高斯模糊,设置模糊度(在0.0到25.0之间)，默认”25";"4":图片缩放比例,默认“1”
        MultiTransformation multi = new MultiTransformation(
                new BlurTransformation(this, 25, 1)
//                new RoundedCorners( 10 ) //设置图片圆角角度
        );


        RequestOptions options = new RequestOptions()
                .placeholder(R.mipmap.no_cover_landscape)
                .bitmapTransform(multi);//.override(300, 400);
//        Glide.with(this)
//                .load(bean.getCoverUrl())
////                .apply(RequestOptions.bitmapTransform(new BlurTransformation(this, 15, 1)))
//                .into(new SimpleTarget<Drawable>() {
//                    @Override
//                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
//                        mRlHead.setBackground(resource);
//
//                    }
//
//                    @Override
//                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
//                        super.onLoadFailed(errorDrawable);
//                    }
//                });
        //书名
        mTvTitle.setText(bean.getTitle());
        //作者
        if (!bean.getAuthor().isEmpty()) {

            mTvAuthor.setText("作者：" + bean.getAuthor());
        }
        //类型
        if (!bean.getCategory().isEmpty()) {
            mTvType.setText((bean.getAuthor().isEmpty() ? "" : "|") + bean.getCategory());
        }

        //总字数
//        mTvWordCount.setText(getResources().getString(R.string.wa_book_word, bean.getWordCount() / 10000));
        if (!bean.getWordCount().isEmpty()) {
            mTvWordCount.setText(((bean.getAuthor().isEmpty() && bean.getCategory().isEmpty()) ? "" : "|") + bean.getWordCount());
        }
        mTvSource.setText("网源：" + mCollBookBean.getSiteSourceBean().getSiteName());
        //更新时间
        if (!StringUtils.isEmpty(bean.getLastUpdated())) {
            mTvLatelyUpdate.setText("最后更新：" + bean.getLastUpdated());
        }else {

            if (!StringUtils.isEmpty(bean.getLastChapter())) {
                mTvLatelyUpdate.setText("最新章节：" + bean.getLastChapter());
            }
        }
        //简介
        if (StringUtils.isEmpty(bean.getDesc())) {
            bean.setDesc("暂无");
        }
        mTvBrief.setText("简介：" + bean.getDesc());
        if (isCollected) {
            mTvAddCollection.setText(getResources().getString(R.string.wa_book_detail_remove_collection));
//            mTvRead.setText(getResources().getString(R.string.wa_book_detail_continue_read));
        } else {
            mTvAddCollection.setText(getResources().getString(R.string.wa_book_detail_collection));
//            mTvRead.setText(getResources().getString(R.string.wa_book_detail_start_read));
        }

        if (inputChapterBeanList != null && !inputChapterBeanList.isEmpty()) {
            updateCatalog(inputChapterBeanList);
            return;
        }
        mCollBookBean.__setDaoSession(DaoDbHelper.getInstance().getSession());
        List<MediaChapterBean> chapterList = mCollBookBean.getMediaChapterList();
        if (chapterList == null || chapterList.isEmpty()) {
            //启用网络获取章节目录信息
            mPresenter.updateWebCatalog(mCollBookBean.getSiteSourceBean(), mCollBookBean);
        } else {
            //本地缓存过了这里 isCollected 是true
            updateCatalog(chapterList);
//            updateCatalogDirectly();
        }
//        mCollBookBean = MediaStorageManager.getInstance().getShelfMedia(bean.getId());
//
//        //判断是否收藏
//        if (mCollBookBean != null) {
//            isCollected = true;
//
//            mTvAddCollection.setText(getResources().getString(R.string.nb_book_detail_give_up));
//            //修改背景
//            Drawable drawable = getResources().getDrawable(R.drawable.shape_common_gray_corner);
//            mTvAddCollection.setBackground(drawable);
//            //设置图片
//            mTvAddCollection.setCompoundDrawables(ContextCompat.getDrawable(this, R.drawable.ic_book_list_delete), null,
//                    null, null);
//            mTvRead.setText("继续阅读");
//        } else {
//            mCollBookBean = bean.getCollBookBean();
//        }
    }

//    @Override
//    public void finishHotComment(List<HotCommentBean> beans) {
//        if (beans.isEmpty()) {
//            return;
//        }
//        mHotCommentAdapter = new HotCommentAdapter();
//        mRvHotComment.setLayoutManager(new LinearLayoutManager(this) {
//            @Override
//            public boolean canScrollVertically() {
//                //与外部ScrollView滑动冲突
//                return false;
//            }
//        });
//        mRvHotComment.addItemDecoration(new DividerItemDecoration(this));
//        mRvHotComment.setAdapter(mHotCommentAdapter);
//        mHotCommentAdapter.addItems(beans);
//    }
//
//    @Override
//    public void finishRecommendBookList(List<BookListBean> beans) {
//        if (beans.isEmpty()) {
//            mTvRecommendBookList.setVisibility(View.GONE);
//            return;
//        }
//        //推荐书单列表
//        mBookListAdapter = new BookListAdapter();
//        mRvRecommendBookList.setLayoutManager(new LinearLayoutManager(this) {
//            @Override
//            public boolean canScrollVertically() {
//                //与外部ScrollView滑动冲突
//                return false;
//            }
//        });
//        mRvRecommendBookList.addItemDecoration(new DividerItemDecoration(this));
//        mRvRecommendBookList.setAdapter(mBookListAdapter);
//        mBookListAdapter.addItems(beans);
//    }

    @Override
    public void waitToBookShelf() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setTitle("正在添加到书架中");
        }
        mProgressDialog.show();
    }

    @Override
    public void errorToBookShelf() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        isCollected = false;
//        mTvRead.setText(getResources().getString(R.string.wa_book_detail_start_read));
        mTvAddCollection.setText(getResources().getString(R.string.wa_book_detail_collection));
        ToastUtils.show("加入书架失败，请检查网络");
    }

    @Override
    public void succeedToBookShelf() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        isCollected = true;
//        mTvRead.setText(getResources().getString(R.string.wa_book_detail_continue_read));
        mTvAddCollection.setText(getResources().getString(R.string.wa_book_detail_remove_collection));
        ToastUtils.show("加入书架成功");
    }

    @Override
    public void showError() {
        mRefreshLayout.showError();
    }

    @Override
    public void complete() {
        mRefreshLayout.showFinish();
    }

    /*******************************************************/
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(EXTRA_COLLECTION_MEDIA, mCollBookBean);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //如果进入阅读页面收藏了，页面结束的时候，就需要返回改变收藏按钮
        if (requestCode == REQUEST_READ) {
            if (data == null) {
                return;
            }

            isCollected = data.getBooleanExtra(RESULT_IS_COLLECTED, false);

            if (isCollected) {
                mTvAddCollection.setText(getResources().getString(R.string.wa_book_detail_remove_collection));
//                //修改背景
//                Drawable drawable = getResources().getDrawable(R.drawable.shape_common_gray_corner);
//                mTvAddCollection.setBackground(drawable);
//                //设置图片
//                mTvAddCollection.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.ic_book_list_delete), null,
//                        null, null);
//                mTvRead.setText(getString(R.string.wa_book_detail_continue_read));
            }
        }
    }

    @Override
    public void updateCatalog(List<MediaChapterBean> mediaChapterBeanList) {
        mData.clear();
        mData.addAll(mediaChapterBeanList);
        mRawData.clear();
        mRawData.addAll(mediaChapterBeanList);
        mCollBookBean.setMediaChapterList(mediaChapterBeanList);
        mDetailCatalogAdapter.notifyDataSetChanged();
        mRefreshLayout.showFinish();

    }

    private void updateCatalogDirectly() {
        mDetailCatalogAdapter.notifyDataSetChanged();
        mRefreshLayout.showFinish();
    }

    @Override
    public void updateCategoryFailed() {

    }

    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxEvent.MEDIA_COLLECTION_ADD),
                    @Tag(RxEvent.MEDIA_COLLECTION_REMOVE),
                    @Tag(RxEvent.MEDIA_COLLECTION_REFRESH)})
    public void onCollectionStateChanged(CollectionMediaBean collectionMediaBean) {
        if (collectionMediaBean.getId().equals(mCollBookBean.getId())) {
            isCollected = true;
            mTvAddCollection.setText(getResources().getString(R.string.wa_book_detail_remove_collection));
        }
    }
}
